package manager.rawdata;


import java.util.Iterator;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import manager.data.LazyPersistedQueue;
import manager.data.RawDataObject;
import manager.utility.PacketParser;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import store.hibernate.RawData;


public class QueueBackupObject {
	
	private static QueueBackupObject instance;
	private SessionFactory factory;
	private LazyPersistedQueue lpq;
	

	public QueueBackupObject(LazyPersistedQueue lpq) {
		this.lpq=lpq;
		try { 
			InitialContext ctx = new InitialContext(); 
			factory = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory"); 
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	
	public boolean remove(){
		Session session = factory.openSession();
	     session.beginTransaction();
	     Query query = session.createQuery("from RawData");
	     query.setMaxResults(1);
	     List<RawData> l = query.list();
	    if(l.get(0)!=null){
	    	RawData rd=l.get(0);
	    	System.out.println("elimino il record "+rd.getIdKey().toString());
	    	session.delete(rd);
	    }
	    session.getTransaction().commit();
	    if (session.isOpen()) 
	          session.close(); 
		return true;
	}


	public boolean loadBackup() {
		Session session = factory.openSession();
			System.out.print("carico la coda");
			Iterator<RawData> a = session.createQuery("from RawData").iterate(); 
			int events=0;
			while(a.hasNext()){
				events++;
				RawData eq2 = a.next();
				byte[] id = eq2.getIdKey();
				byte[] cont = eq2.getContenuto();

				PacketParser pp = PacketParser.getInstance();
				RawDataObject rdo = pp.create(id, cont);
				if(rdo!=null){
					lpq.push(rdo);
					lpq.loadEvents();
					System.out.println(" di "+events+" eventi");
				}
				else
					session.delete(eq2);
			}
		if (session.isOpen()) 
			session.close(); 
		return true;
	}
	
	
	public boolean insertBlock() {
		Session session = factory.openSession();
	     session.beginTransaction();
	     int size = lpq.memorySizeTmp();
	     for(int i=0;i<size;i++){
	    	 RawDataObject rdo = lpq.popTmp();
	    	 if(rdo!=null){
	    	 	RawData rd = new RawData(rdo.getKey(),rdo.getContent());
	    	 	session.save(rd);
	    	 }
	     }
		System.out.println("inserisco in raw "+size+ " record...");
	    session.getTransaction().commit();
	    if (session.isOpen()) 
	          session.close(); 
		return true;
	}
	
	public static synchronized QueueBackupObject getInstance(LazyPersistedQueue lpq){
		if(instance==null)
			instance=new QueueBackupObject(lpq);
		return instance;
	} 
}
